//
//  NCSinglePictureViewer.m
//  BaiduTravel
//
//  Created by bilinguis on 12-2-2.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "NCSinglePictureViewer.h"
#import "NCPictureViewerBar.h"
#import "NCBTImage.h"
#import "LSLabel.h"
#import "UIImageView+CutToResize.h"
#import "NSString+NSString_Ex_.h"
#import "AppDelegate.h"

#define ZOOM_STEP                           1.5
#define ZOOM_VIEW_TAG                       100

#define kInfoBarImageFrame                  CGRectMake(0, 0, 320, 45)
#define kScrollViewFrame                    CGRectMake(0, 0, 320, UIScreenHeight - 20)
#define kScrollViewFrameEx                  CGRectMake(0, 0, 320, UIScreenHeight)
#define kNaviBarSearchBtnCenter		        CGPointMake(288, 22)


#define kScreenWidth                        320
#define kScreenHeight                       (UIScreenHeight - 20)
#define kScreenHeightEx                     (UIScreenHeight)


#define kWaitingImageName                   @"lv_image_default_background.png"
#define kWaitingImageWidth                  300
#define kWaitingImageHeight                 200


#define kTitleImageFile                     @"picture_title_icon.png"
#define kPosImageFile                       @"picture_location_icon.png"

#define kTitleImageViewFrame                CGRectMake(10, 7, 20, 18)
#define kTitleLabelFrame                    CGRectMake(35, 5, 140, 20)
#define kPosImageViewFrame                  CGRectMake(195, 6, 20, 18)//114.7.26.26
#define kPosLabelFrame                      CGRectMake(220, 5, 100, 20)

#define kTitleBgTag 100
#define kTitleImageTag 150
#define kTitleTag   200
#define kAddressTag 300
#define kPosImageTag 400

@interface NCSinglePictureViewer (UtilityMethods)
- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center;
@end

@implementation NCSinglePictureViewer
@synthesize imageScrollView = _imageScrollView;
@synthesize imageView = _imageView;
@synthesize picUrl = _picUrl;
@synthesize pic_id = _pic_id, pic_title = _pic_title, pic_location = _pic_location;
@synthesize saveStateEnable;
@synthesize fScreenHeight = _fScreenHeight;
@synthesize scrollViewFrame = _scrollViewFrame;
@synthesize touchDelegate = _touchDelegate;
@synthesize waitingImage = _waitingImage;


- (void) initViews
{
    UIButton *backgroundButton = [[[UIButton alloc] initWithFrame:self.scrollViewFrame] autorelease];
    backgroundButton.backgroundColor = [UIColor clearColor];
//    [backgroundButton addTarget:self action:@selector(backgroundButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    _backgroundButton = backgroundButton;
    [backgroundButton addSubview:_imageView];
    [_imageScrollView addSubview:backgroundButton];
    
    [self.view addSubview:_imageScrollView];
}


- (void)autoCenter
{
    // 这段实现是不是有问题啊
    /*
     if ([_imageScrollView contentSize].width <= 320 || [_imageScrollView contentSize].height <=460) 
     {
     CGRect rect = _imageScrollView.frame;
     rect.size.width = [_imageScrollView contentSize].width;
     rect.size.height = [_imageScrollView contentSize].height;
     rect.origin.x = -( 320 - [_imageScrollView contentSize].width )/2;
     rect.origin.y = -( 460 - [_imageScrollView contentSize].height)/2;
     
     _imageScrollView.contentOffset = rect.origin;
     }
     */
    _imageView.center = _imageScrollView.center;
}

- (void)hideOriNaviReturnBtn
{
    UIView *tmpView = [[UIView alloc] initWithFrame:CGRectZero];
    UIBarButtonItem *backItem = [[[UIBarButtonItem alloc] initWithCustomView:tmpView] autorelease];
    self.navigationItem.leftBarButtonItem = backItem;
    [tmpView release];
}

- (void)backButtonClicked
{

//    [_imageView cancelRequest];
}


-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
//    [_imageView cancelRequest];
}
- (void) createImageScrollView
{
    if (_imageScrollView == nil)
    {
        UIScrollView* imageScrollView=[[UIScrollView alloc] initWithFrame:self.scrollViewFrame] ;
        self.imageScrollView = imageScrollView;
        [imageScrollView release];
    }
    _imageScrollView.backgroundColor = [UIColor blackColor];
    _imageScrollView.delegate = self;
    _imageScrollView.bouncesZoom = YES;
    _imageScrollView.delaysContentTouches = YES;
    _imageScrollView.canCancelContentTouches = YES;
    _imageScrollView.multipleTouchEnabled = YES;
    _imageScrollView.clearsContextBeforeDrawing = YES;
    [_imageScrollView setScrollEnabled:YES];
    [_imageScrollView setShowsVerticalScrollIndicator:YES];
    _imageScrollView.contentSize = CGSizeZero;
    
    if (_imageView == nil)
    {
        NCBTImage *imageView = [[NCBTImage alloc] initWithFrame:CGRectMake(0, 0,kScreenWidth, self.fScreenHeight)];
        imageView.isShowOriginDownloadPic = YES;
        imageView.userInteractionEnabled = YES;
        
        if (imageView.frame.size.width <= 320 && imageView.frame.size.height <= self.fScreenHeight)
        {
            CGFloat x = _imageScrollView.frame.size.width / 2.0;
            CGFloat y = _imageScrollView.frame.size.height / 2.0;
            imageView.center = CGPointMake(x, y);
        }
        [imageView setTag:ZOOM_VIEW_TAG];
        
       
        /*UITapGestureRecognizer *twoFingerTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTwoFingerTap:)];
        
        [twoFingerTap setNumberOfTouchesRequired:2];
        
        [imageView addGestureRecognizer:twoFingerTap];
        
        [twoFingerTap release];*/
        
        _imageView = imageView;
    }
}

-(void) ImageResetCallBack:(NCBTImage *)pic
{
    if (pic)
    {
        if (!pic.image)
        {
            [_imageView removeFromSuperview];
            return;
        }
        
        // 下载图片成功，重新设置大小
        _originSize = pic.frame.size;
        
        
        // 隐藏占位图
        [_watingImageView removeFromSuperview];
        [_watingImageView release];
        _watingImageView = nil;
        saveStateEnable = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ImageDownloaded" object:nil];
        // 记录一下大小，然后再次调用适配屏幕
        //[self ImageResetCallBack:nil];
        /*
         }
         else
         {
         */
//        [_imageScrollView addSubview:_imageView];
//        [_imageView insertSubview:(UIView *) atIndex:
        if (_originSize.width==0 || _originSize.height==0)
        {
            [_imageScrollView setContentSize:CGSizeMake(kScreenWidth,self.fScreenHeight)];
        }
        else
        {
            [_imageScrollView setContentSize:_originSize];
        }
        // 重新设置大小，改为适配屏幕
        float widthDivideHeight=kScreenWidth/self.fScreenHeight;
        float picWidthDivideHeight = _originSize.width / _originSize.height;
        if (widthDivideHeight > picWidthDivideHeight)
        {
            // 大图看起来太窄了。
            if (_originSize.height > self.fScreenHeight)
            {
                //又窄又高。需要压缩高度
                //NSLog(@"_originSize.height > self.fScreenHeight");
                CGFloat rate=self.fScreenHeight / _originSize.height;
                //CGFloat scale = 63.0 / _originSize.height;
                [_imageScrollView setMinimumZoomScale:rate];
                [_imageScrollView setZoomScale:rate];
            }
            else
            {
                //不够高。不用压缩高度就能显示完整。
                [_imageScrollView setMinimumZoomScale:1.0];
                [_imageScrollView setZoomScale:1.0];
            }
        }
        else
        {
            // 大图相对来说太宽，压缩宽度
            //NSLog(@"else _originSize.height > self.fScreenHeight");
            if (_originSize.width > kScreenWidth)
            {
                CGFloat rate = kScreenWidth / _originSize.width;
                //CGFloat scale = 88.0 / _originSize.width;
                [_imageScrollView setMinimumZoomScale:rate];
                [_imageScrollView setZoomScale:rate];
            }
            else
            {
                // 宽度不够屏幕
                [_imageScrollView setMinimumZoomScale:1.0];
                [_imageScrollView setZoomScale:1.0];
            }
        }
        // 调整图片的坐标，使其显示在屏幕中央
        //if (_imageView.frame.size.width <= 320 && _imageView.frame.size.height <= 460) 
        {
            CGFloat x = _imageScrollView.frame.size.width / 2.0;
            CGFloat y = _imageScrollView.frame.size.height / 2.0;
            _imageView.center = CGPointMake(x, y);
        }
        
    }
    //[self autoCenter];
}

- (void)loadView 
{
    [super loadView];
    
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor blackColor];
    
    [self initViews];
    
    // set the pic varables.
    //NSLog(@"large pic url:%@",self.picUrl);
    [_imageView setCallbackOnDownloadFinished:self withSelector:@selector(ImageResetCallBack:)];
    
    saveStateEnable = NO;
    // 设置占位图
    if (_watingImageView == nil)
    {
        _watingImageView = [[UIImageView alloc] init];
        CGRect rect = CGRectZero;
        rect.origin.x = (kScreenWidth - kWaitingImageWidth) / 2.0;
        rect.origin.y = (self.fScreenHeight - kWaitingImageHeight) / 2.0;
        rect.size.width = kWaitingImageWidth;
        rect.size.height = kWaitingImageHeight;
        _watingImageView.frame = rect;
        _watingImageView.backgroundColor = [UIColor redColor];
        UIImage *waitingImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image_default.png" ofType:nil]];
        [_watingImageView setImage:waitingImage];
        if ( _waitingImage ) {
            rect.origin.x = 0;
            rect.origin.y = 0;
            rect.size = CGSizeMake(320,UIScreenHeight);
            _watingImageView.frame = rect;
            _watingImageView.contentMode = UIViewContentModeScaleAspectFit;
            [_watingImageView setImage:_waitingImage];
        }
        [self.view addSubview:_watingImageView];
        KFLog(@"waiting image view rect %@，image size %@",NSStringFromCGRect(_watingImageView.frame),NSStringFromCGSize(_watingImageView.image.size));
    }
   
    [self hideOriNaviReturnBtn];
    
    // 开始下载图片
    if (![self.picUrl hasPrefix:@"http"]) {
        if ([self.picUrl hasPrefix:@"file"])
        {
            NSURL* url = [NSURL URLWithString:self.picUrl];
            [_imageView setDownLoadOrginPic:[UIImage imageWithContentsOfFile:[url path]]];
            [_imageView downloadFinished];
        }
        else
        {
            [_imageView setDownLoadOrginPic:[UIImage imageWithContentsOfFile:self.picUrl]];
            [_imageView downloadFinished];
        }
    }
    else
        _imageView.url = self.picUrl;
    //[self addPicTitle:self.pic_title andPicLocation:self.pic_location ToViewBottom:_imageScrollView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backButtonClicked) name:@"CancelImageLoading" object:nil];
    
}


#pragma 
#pragma mark - 加入图片 title 和 location
-(void ) addPicTitle:(NSString*)picTitle andPicLocation:(NSString*)location ToViewBottom:(UIView*)target
{
    CGRect imageFrame = target.frame;
    
    UIView  *container = [[UIView alloc] initWithFrame:CGRectMake(0, imageFrame.origin.y+imageFrame.size.height-30, 320, 30)];
    
    CGFloat titleNewHeight ,locationNewHeight;
    titleNewHeight = locationNewHeight = 0;
    
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [bgView setBackgroundColor:[UIColor blackColor]];
    bgView.alpha = 0.5;
    [container addSubview:bgView];
    bgView.hidden = NO;
    [bgView release];
    
    
    if (![picTitle isEqualToString:@""]) {
        UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:kTitleImageFile]];
        titleImageView.backgroundColor = [UIColor clearColor];
        titleImageView.frame = kTitleImageViewFrame;
        [container addSubview:titleImageView];
        [titleImageView release];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:kTitleLabelFrame];
        titleLabel.text = picTitle;
        titleLabel.backgroundColor = [UIColor clearColor];
        [titleLabel setTextColor:[UIColor whiteColor]];
        [titleLabel setFont:[UIFont systemFontOfSize:16]];
        [container addSubview:titleLabel];
        
        titleNewHeight = [NCSinglePictureViewer calculateTextHeight:titleLabel];
        titleLabel.frame = CGRectMake(titleLabel.frame.origin.x, titleLabel.frame.origin.y, titleLabel.frame.size.width, titleNewHeight);
        
        [titleLabel release];
        
    }
    
    
    
    UILabel *addressLabel = [[UILabel alloc] initWithFrame:kPosLabelFrame];
    UIImageView *posImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:kPosImageFile]];
    if (![location isEqualToString:@""]) {
        posImageView.backgroundColor = [UIColor clearColor];
        posImageView.frame = kPosImageViewFrame;
        [container addSubview:posImageView];
        
        addressLabel.text = location;
        [addressLabel setFont:[UIFont systemFontOfSize:16]];
        addressLabel.backgroundColor = [UIColor clearColor];
        [addressLabel setTextColor:[UIColor whiteColor]];
        [container addSubview:addressLabel];
        
        
        locationNewHeight = [NCSinglePictureViewer calculateTextHeight:addressLabel];
        addressLabel.frame = CGRectMake(addressLabel.frame.origin.x, addressLabel.frame.origin.y, addressLabel.frame.size.width, locationNewHeight);
        
        
    }
    
    
    //    [self addViewToScrollView:container leftAlignment:0 isTitleView:NO isNotePostTitle:NO];
    [container setBackgroundColor:[UIColor clearColor]];
    
    if (titleNewHeight > locationNewHeight) {
        container.frame = CGRectMake(0, imageFrame.origin.y+imageFrame.size.height-titleNewHeight-10-40, 320, titleNewHeight+10);
        bgView.frame = CGRectMake(bgView.frame.origin.x, bgView.frame.origin.y, bgView.frame.size.width, titleNewHeight+10);
    }else{
        container.frame = CGRectMake(0, imageFrame.origin.y+imageFrame.size.height-locationNewHeight-10-40, 320, locationNewHeight+10);
        bgView.frame = CGRectMake(bgView.frame.origin.x, bgView.frame.origin.y, bgView.frame.size.width, locationNewHeight+10);
    }
    if (titleNewHeight == locationNewHeight && titleNewHeight == 0) {
        [container setAlpha:1];
        container.hidden = YES;
    }
    
    //如果location文字较短，靠右对齐
    if (locationNewHeight > 0) {
        CGSize newSize = [location sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(100, 300) lineBreakMode:UILineBreakModeWordWrap];
        addressLabel.frame = CGRectMake(320-newSize.width, addressLabel.frame.origin.y, newSize.width, newSize.height);
        posImageView.center=CGPointMake(posImageView.center.x+100-newSize.width, posImageView.center.y);
    }
    
    [posImageView release];
    [addressLabel release];
    [self.view insertSubview:container aboveSubview:target];
    [container release];
}

-(UIView *) addPicTitleWithStartFrame:(NSString*)picTitle andPicLocation:(NSString*)location startFrame:(CGRect)startFrame
{
    CGRect imageFrame = startFrame;
    
    UIView  *container = [[UIView alloc] initWithFrame:CGRectMake(0, imageFrame.origin.y+imageFrame.size.height, 320, 30)];
    container.alpha = 1.0;
    
    CGFloat titleNewHeight ,locationNewHeight;
    titleNewHeight = locationNewHeight = 0;
    
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
    [bgView setBackgroundColor:[UIColor clearColor]];
    bgView.alpha = 1.0;
    bgView.tag = kTitleBgTag;
    [container addSubview:bgView];
    bgView.hidden = NO;
    [bgView release];
    
    if (![picTitle isEqualToString:@""]) {
        UIImageView *titleImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:kTitleImageFile]];
        titleImageView.backgroundColor = [UIColor clearColor];
        titleImageView.frame = kTitleImageViewFrame;
        titleImageView.tag = kTitleImageTag;
        [container addSubview:titleImageView];
        [titleImageView release];

        UILabel *titleLabel = [[UILabel alloc] initWithFrame:kTitleLabelFrame];
        titleLabel.text = picTitle;
        titleLabel.backgroundColor = [UIColor clearColor];
        [titleLabel setTextColor:[UIColor whiteColor]];
        [titleLabel setFont:[UIFont systemFontOfSize:16]];
        titleLabel.tag = kTitleTag;
        [container addSubview:titleLabel];
        
        titleNewHeight = [NCSinglePictureViewer calculateTextHeight:titleLabel];
        titleLabel.frame = CGRectMake(titleLabel.frame.origin.x, titleLabel.frame.origin.y, titleLabel.frame.size.width, titleNewHeight);
        
        [titleLabel release];
    }
    
    
    UILabel *addressLabel = [[UILabel alloc] initWithFrame:kPosLabelFrame];
    UIImageView *posImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:kPosImageFile]];
    posImageView.tag = kPosImageTag;
    if (![location isEqualToString:@""]) {
        posImageView.backgroundColor = [UIColor clearColor];
        posImageView.frame = kPosImageViewFrame;
        [container addSubview:posImageView];
        
        addressLabel.text = location;
        [addressLabel setFont:[UIFont systemFontOfSize:16]];
        addressLabel.backgroundColor = [UIColor clearColor];
        [addressLabel setTextColor:[UIColor whiteColor]];
        addressLabel.tag = kAddressTag;
        [container addSubview:addressLabel];
        
        
        locationNewHeight = [NCSinglePictureViewer calculateTextHeight:addressLabel];
        addressLabel.frame = CGRectMake(addressLabel.frame.origin.x, addressLabel.frame.origin.y, addressLabel.frame.size.width, locationNewHeight);
    }
    
    
    //    [self addViewToScrollView:container leftAlignment:0 isTitleView:NO isNotePostTitle:NO];
    [container setBackgroundColor:[UIColor clearColor]];

    if (titleNewHeight > locationNewHeight) {
        container.frame = CGRectMake(0, 0, 320, titleNewHeight+10);
        bgView.frame = CGRectMake(bgView.frame.origin.x, bgView.frame.origin.y, bgView.frame.size.width, titleNewHeight+10);
    }else{
        container.frame = CGRectMake(0,0, 320, locationNewHeight+10);
        bgView.frame = CGRectMake(bgView.frame.origin.x, bgView.frame.origin.y, bgView.frame.size.width, locationNewHeight+10);
    }
    if (titleNewHeight == locationNewHeight && titleNewHeight == 0) {
        [container setAlpha:1];
        container.hidden = YES;
    }
    
    //如果location文字较短，靠右对齐
    if (locationNewHeight > 0) {
       CGSize newSize = [location sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(100, 300) lineBreakMode:UILineBreakModeWordWrap];
        addressLabel.frame = CGRectMake(320-newSize.width, addressLabel.frame.origin.y, newSize.width, newSize.height);
        posImageView.center=CGPointMake(posImageView.center.x+100-newSize.width, posImageView.center.y);
    }
    
    [posImageView release];
    [addressLabel release];
    
    [self setPicTitleAndLocation:container andTitle:picTitle andPicLocation:location];
    
    return [container autorelease];
}

-(void) setPicTitleAndLocation:(UIView *)titleView andTitle:(NSString *)title andPicLocation:(NSString *)location
{
    UIView  *container = titleView;
    container.alpha = 1.0;
    
    CGFloat titleNewHeight ,locationNewHeight;
    titleNewHeight = locationNewHeight = 0;
    
    
    UIView *bgView = [container viewWithTag:kTitleBgTag];
    
    UILabel *titleLabel = (UILabel *)[container viewWithTag:kTitleTag];
    UIImageView *titleImageView = (UIImageView *)[container viewWithTag:kTitleImageTag];
    if (![NSString stringIsNullOrEmpty:title]) {
        titleLabel.text = title;
        titleImageView.hidden = NO;
        
        titleNewHeight = [NCSinglePictureViewer calculateTextHeight:titleLabel];
        titleLabel.frame = CGRectMake(titleLabel.frame.origin.x, titleLabel.frame.origin.y, titleLabel.frame.size.width, titleNewHeight);
    } else {
        titleImageView.hidden = YES;
        titleLabel.text = @"";
    }
    
    UILabel *addressLabel = (UILabel *)[container viewWithTag:kAddressTag];
    UIImageView *posImageView = (UIImageView *)[container viewWithTag:kPosImageTag];
    if (![NSString stringIsNullOrEmpty:location]) {
        addressLabel.text = location;
        posImageView.hidden = NO;
        posImageView.frame = kPosImageViewFrame;
        
        locationNewHeight = [NCSinglePictureViewer calculateTextHeight:addressLabel];
        addressLabel.frame = CGRectMake(addressLabel.frame.origin.x, addressLabel.frame.origin.y, addressLabel.frame.size.width, locationNewHeight);
    } else {
        addressLabel.text = @"";
        posImageView.hidden = YES;
    }
    
    if (titleNewHeight > locationNewHeight) {
        container.frame = CGRectMake(0, 0, 320, titleNewHeight+10);
        bgView.frame = CGRectMake(bgView.frame.origin.x, bgView.frame.origin.y, bgView.frame.size.width, titleNewHeight+10);
    }else{
        container.frame = CGRectMake(0,0, 320, locationNewHeight+10);
        bgView.frame = CGRectMake(bgView.frame.origin.x, bgView.frame.origin.y, bgView.frame.size.width, locationNewHeight+10);
    }
    if (titleNewHeight == locationNewHeight && titleNewHeight == 0) {
        [container setAlpha:1];
        container.hidden = YES;
    } else {
        container.hidden = NO;
    }
    
    //如果location文字较短，靠右对齐
    if (locationNewHeight > 0) {
        CGSize newSize = [location sizeWithFont:[UIFont systemFontOfSize:16] constrainedToSize:CGSizeMake(100, 300) lineBreakMode:UILineBreakModeWordWrap];
        addressLabel.frame = CGRectMake(320-newSize.width, addressLabel.frame.origin.y, newSize.width, newSize.height);
        posImageView.center=CGPointMake(posImageView.center.x+100-newSize.width, posImageView.center.y);
    }
}


+ (CGFloat) calculateTextHeight:(UILabel*)textField
{
    textField.numberOfLines = 0;
    
     LSLabel *_notesLabel = [[LSLabel alloc] init];
    [_notesLabel setFont:textField.font];
    _notesLabel.textAlignment = UITextAlignmentLeft;
    
    _notesLabel.text = textField.text;
    _notesLabel.frame = CGRectMake(0, 0, textField.frame.size.width, 0);//宽度高度只需指定其一
    float height = _notesLabel.frame.size.height;
    [_notesLabel release];
    return height;
}

- (void)saveButtonClicked
{
    saveStateEnable = NO;
    UIImageWriteToSavedPhotosAlbum(_imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
}

-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (error != NULL) {
//        NSLog(@"save photo error %@",error.domain);
        if (error.code == -3310) {
            
            [RCAppDelegate alertWithCustomizeString:@"保存图片失败，没有访问相册权限"];
        }else{
            
            [RCAppDelegate alertWithCustomizeString:@"保存图片失败"];
        }
    }else{
        
        [RCAppDelegate alertWithCustomizeString:@"图片已保存到手机相册"];
    }
}

//
//- (void)showPicInfoBarAnimated:(BOOL)animated
//{
//    if (animated)
//	{
//		[UIView beginAnimations:nil context:NULL];
//		[UIView setAnimationDuration:0.3];
//	}
//	container.alpha = 1.0;
//	if (animated)
//	{
//		[UIView commitAnimations];
//	}
//    container.hidden = NO;
//}
//
//
//- (void) hidePicInfoBarAnimated:(BOOL)animated
//{
//    if (animated)
//	{
//		[UIView beginAnimations:nil context:NULL];
//		[UIView setAnimationDuration:0.3];
//	}
//
//	container.alpha = 0.0;
//	if (animated)
//	{
//		[UIView commitAnimations];
//	}
//    container.hidden = YES;
//}


- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
    self.navigationController.navigationBarHidden = YES;
}


- (void)viewDidUnload {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"CancelImageLoading" object:nil];
    [_imageView setCallbackOnDownloadFinished:nil withSelector:nil];

	self.imageScrollView = nil;
	self.imageView = nil;
    [_watingImageView release];
    _watingImageView = nil;
    self.waitingImage = nil;
//    [container release]; container = nil;
    [super viewDidUnload];
}


- (void)dealloc {
    [_imageView setCallbackOnDownloadFinished:nil withSelector:nil];
    [_pic_id            release];
    [_pic_location      release];
    [_pic_title         release];
    [_picUrl            release];
    
    self.imageScrollView = nil;
    [_imageView         release];
    [_watingImageView   release];
    _watingImageView    = nil;
//    [container release]; container = nil;
    self.touchDelegate = nil;
    self.waitingImage = nil;
    [super dealloc];
}

#pragma mark UIScrollViewDelegate methods


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if ( _touchDelegate && [_touchDelegate respondsToSelector:@selector(pictureZoomBegan)] ) {
        [_touchDelegate pictureZoomBegan];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollViewT
{
    if ( _touchDelegate && [_touchDelegate respondsToSelector:@selector(pictureZoomEnded)] ) {
        [_touchDelegate pictureZoomEnded];
    }
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return [_imageScrollView viewWithTag:ZOOM_VIEW_TAG];
}

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view
{
    if ( _touchDelegate && [_touchDelegate respondsToSelector:@selector(pictureZoomBegan)] ) {
        [_touchDelegate pictureZoomBegan];
    }
}

/************************************** NOTE **************************************/
/* The following delegate method works around a known bug in zoomToRect:animated: */
/* In the next release after 3.0 this workaround will no longer be necessary      */
/**********************************************************************************/
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {
    [scrollView setZoomScale:scale+0.01 animated:NO];
    [scrollView setZoomScale:scale animated:NO];
    
    // 修改backgroudButton的大小
    if (_imageView.frame.size.height < self.fScreenHeight) 
    {
        CGRect buttonRect = _backgroundButton.frame;
        buttonRect.size.width = _imageView.frame.size.width;
        _backgroundButton.frame = buttonRect;
    }
    
    // 调整图片的显示位置
    if (_imageView.frame.size.width <= 320 && _imageView.frame.size.height <= self.fScreenHeight) 
    {
        CGFloat x = _imageScrollView.frame.size.width / 2.0;
        CGFloat y = _imageScrollView.frame.size.height / 2.0;
        _imageView.center = CGPointMake(x, y);
    }
    else
    {
        CGPoint point = _imageView.center;
        point.x = _imageView.frame.size.width / 2.0;
        point.y = _imageView.frame.size.height / 2.0;
        _imageView.center = point;
        
        if (_imageView.frame.size.height < self.fScreenHeight)
        {
            CGRect rect = _imageView.frame;
            rect.origin.y = (_imageScrollView.frame.size.height - _imageView.frame.size.height)/2.0;
            _imageView.frame = rect;
        }
        if (_imageView.frame.size.width < 320) 
        {
            CGRect rect = _imageView.frame;
            rect.origin.x = (_imageScrollView.frame.size.width - _imageView.frame.size.width)/2.0;
            _imageView.frame = rect;
        }
    }
    //[NSTimer scheduledTimerWithTimeInterval:0.1e-30 target:self selector:@selector(autoCenter) userInfo:nil repeats:NO];
    
    if ( _touchDelegate && [_touchDelegate respondsToSelector:@selector(pictureZoomEnded)] ) {
        [_touchDelegate pictureZoomEnded];
    }
}

#pragma mark TapDetectingImageViewDelegate methods
/*
- (void)handleTwoFingerTap:(UIGestureRecognizer *)gestureRecognizer {
    if (_originSize.width >320 && _originSize.height > self.fScreenHeight)
    {
        // two-finger tap zooms out
        float newScale = [_imageScrollView zoomScale] / ZOOM_STEP;
        CGPoint point = CGPointMake(_imageScrollView.contentSize.width / 2.0, _imageScrollView.contentSize.height);
        //CGRect zoomRect = [self zoomRectForScale:newScale withCenter:[gestureRecognizer locationInView:gestureRecognizer.view]];
        CGRect zoomRect = [self zoomRectForScale:newScale withCenter:point];
        
        [_imageScrollView zoomToRect:zoomRect animated:YES];
        [_imageScrollView setZoomScale:newScale animated:YES];
        
        if (_imageView.frame.size.width <= 320 && _imageView.frame.size.height <= self.fScreenHeight) 
        {
            CGFloat x = _imageScrollView.frame.size.width / 2.0;
            CGFloat y = _imageScrollView.frame.size.height / 2.0;
            _imageView.center = CGPointMake(x, y);
        }
        else
        {
            CGPoint point = CGPointMake(0, 0);
            point.x = _imageView.frame.size.width / 2.0;
            point.y = _imageView.frame.size.height / 2.0;
            _imageView.center = point;
            
            if (_imageView.frame.size.height < self.fScreenHeight) 
            {
                CGRect rect = _imageView.frame;
                rect.origin.y = (_imageScrollView.frame.size.height - _imageView.frame.size.height)/2.0;
                _imageView.frame = rect;
            }
            if (_imageView.frame.size.width < 320) 
            {
                CGRect rect = _imageView.frame;
                rect.origin.x = (_imageScrollView.frame.size.width - _imageView.frame.size.width)/2.0;
                _imageView.frame = rect;
            }
            
        }
        
    }
}*/

#pragma mark Utility methods

- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center {
    
    CGRect zoomRect;
    
    // the zoom rect is in the content view's coordinates. 
    //    At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds.
    //    As the zoom scale decreases, so more content is visible, the size of the rect grows.
    zoomRect.size.height = [_imageScrollView contentSize].height / scale;
    zoomRect.size.width  = [_imageScrollView contentSize].width  / scale;
    
    // choose an origin so as to get the right center.
    //zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    //zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);
    
    if (_imageView.frame.size.width <= 320 && _imageView.frame.size.height <= self.fScreenHeight) 
    {
        CGFloat x = _imageScrollView.frame.size.width / 2.0;
        CGFloat y = _imageScrollView.frame.size.height / 2.0;
        _imageView.center = CGPointMake(x, y);
    }
    else
    {
        CGPoint point = _imageView.center;
        point.x = _imageView.frame.size.width / 2.0;
        point.y = _imageView.frame.size.height / 2.0;
        _imageView.center = point;
        
        if (_imageView.frame.size.height < self.fScreenHeight)
        {
            CGRect rect = _imageView.frame;
            rect.origin.y = (_imageScrollView.frame.size.height - _imageView.frame.size.height)/2.0;
            _imageView.frame = rect;
        }
        if (_imageView.frame.size.width < 320) 
        {
            CGRect rect = _imageView.frame;
            rect.origin.x = (_imageScrollView.frame.size.width - _imageView.frame.size.width)/2.0;
            _imageView.frame = rect;
        }
        
    }
    return zoomRect;
}


-(id) initWithUrl:(NSString *)url AndPicID:(NSString *)PID Title:(NSString *)title Location:(NSString *)location
{
    _fScreenHeight = kScreenHeight;
    _scrollViewFrame = kScrollViewFrame;
    self = [super init];
    if (self) {
        [self createImageScrollView];        
        _pic_title      = [[NSString alloc]initWithString:title?title:@""];
        _pic_location   = [[NSString alloc]initWithString:location?location:@""];
        _pic_id         = [[NSString alloc]initWithString:PID?PID:@""];
        _picUrl         = [[NSString alloc]initWithString:url?url:@""];
    }
    return self;
}

- (id) init
{
    _fScreenHeight = kScreenHeight;
    _scrollViewFrame = kScrollViewFrame;
    self = [super init];
    if (self)
    {
        [self createImageScrollView]; 
        _imageMinWidth = 200;
    }
    return self;
}

- (id)superInit
{
    self = [super init];
    return self;
}

@end

@implementation NCSinglePictureViewerFullScreen

- (id)initWithUrl:(NSString *)url AndPicID:(NSString *)PID Title:(NSString *)title Location:(NSString *)location
{
    self = [super superInit];
    self.wantsFullScreenLayout = YES;
    if (self) {
        self.fScreenHeight = kScreenHeightEx;
        self.scrollViewFrame = kScrollViewFrameEx;
        
        [self createImageScrollView];
        _pic_title      = [[NSString alloc]initWithString:title?title:@""];
        _pic_location   = [[NSString alloc]initWithString:location?location:@""];
        _pic_id         = [[NSString alloc]initWithString:PID?PID:@""];
        _picUrl         = [[NSString alloc]initWithString:url?url:@""];
    }
    return self;
}

-(void) dealloc
{
    [super dealloc];
}

@end